<template>
  <div id='LuckyExcelForm'>
    <!-- tab基本信息表单  -->
    <el-scrollbar style='height: 100%'>
      <div v-show='!isHidden' style='position: absolute; top: 0'>
        <span>上传：</span><input id='uploadBtn' type='file' @change='loadExcel' />
        <button @click='downloadFile'>下载后编辑</button>
      </div>
      <div id='luckysheet'></div>
    </el-scrollbar>
  </div>
</template>


<script lang='ts' setup>
// 引入组件区==========
import { getCurrentInstance, reactive, ref } from 'vue';
import LuckyExcel from 'luckyexcel';
import { exportExcel } from '@/components/js/luckyExcelExport';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import axios from 'axios';
import Excel from 'exceljs';

const jsonData = ref({});

// 方法定义区 =============
defineExpose({ initExcel, submitExcel, hiddenUpload });


// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let isHidden = ref(false);
let internalFileUrl = ref('');

/**
 * 左侧表格点击当前行传过来的数据
 * @param fileUrl
 */
function initExcel(fileUrl: string) {
  isHidden.value = false;
  internalFileUrl.value = fileUrl;
  window.luckysheet.destroy();
  if (fileUrl) {
    fetchExcel(fileUrl);
  } else {
    window.luckysheet.create({
      container: 'luckysheet',
      showinfobar: false
    });
  }
}

function hiddenUpload(hidden: boolean) {
  isHidden.value = hidden;
}

function loadExcel(evt) {
  const files = evt.target.files;
  if (files == null || files.length == 0) {
    alert('No files wait for import');
    return;
  }

  let name = files[0].name;
  let suffixArr = name.split('.'),
    suffix = suffixArr[suffixArr.length - 1];
  if (suffix != 'xlsx') {
    alert('Currently only supports the import of xlsx files');
    return;
  }
  LuckyExcel.transformExcelToLucky(files[0], function(exportJson, luckysheetfile) {
    if (exportJson.sheets == null || exportJson.sheets.length == 0) {
      alert('Failed to read the content of the excel file, currently does not support xls files!');
      return;
    }
    jsonData.value = exportJson;

    window.luckysheet.destroy();

    window.luckysheet.create({
      container: 'luckysheet',
      showinfobar: false,
      data: exportJson.sheets,
      title: exportJson.info.name,
      userInfo: exportJson.info.name.creator
    });
  });
}

function fetchExcel(fileUrl: string) {
  LuckyExcel.transformExcelToLuckyByUrl(fileUrl, 'excel.xlsx', (exportJson, luckysheetfile) => {
    if (exportJson.sheets == null || exportJson.sheets.length == 0) {
      alert('Failed to read the content of the excel file, currently does not support xls files!');
      return;
    }
    jsonData.value = exportJson;

    window.luckysheet.destroy();

    window.luckysheet.create({
      container: 'luckysheet',
      showinfobar: false,
      data: exportJson.sheets,
      title: exportJson.info.name,
      userInfo: exportJson.info.name.creator
    });
  });
}

function submitExcel(callback) {
  const workbook = new Excel.Workbook();
  const fileName = new Date().getTime().toString() + '.xlsx';

  exportExcel(workbook, window.luckysheet.getAllSheets());
  workbook.xlsx.writeBuffer().then(data => {
    const blob = new Blob([data], {
      type: 'application/vnd.ms-excel;charset=utf-8'
    });
    const formData = new FormData();
    formData.append('file', blob, fileName);
    axios.post(
      (window as any).apiUrl.VITE_SERVER_URL + '/file/upload',
      formData,
      { headers: { 'Content-Type': 'multipart/form-data' } }
    ).then(response => {
      VxeMessage('模板上传成功', VxeNotifyType.success);
      callback((window as any).apiUrl.VITE_SERVER_URL + '/file/reload/' + fileName);
    }).catch(error => {
      VxeMessage('模板上传过程中出现错误', VxeNotifyType.error);
    });
  });
}

function downloadFile() {
  if (internalFileUrl.value) {
    window.location.href = internalFileUrl.value;
    // window.open(internalFileUrl.value)
  }
}
</script>

<style lang='scss' scoped>
#LuckyExcelForm {
  padding: 0;
  height: 100%;

  :deep(.el-scrollbar__view) {
    height: 100%;
    //右侧基本信息 保存按钮
    .saveBtn {
      margin: 10px 0 10px 20px;
    }

    .el-form {
      padding: 0 10px;
    }

    .el-row {
      margin-left: 0 !important;
      margin-right: 0 !important;
      // 基本信息表单 备注描述
      .remarkDescriptions {
        width: 600px;
        margin-left: 10px;
      }
    }

    .calcTextArea {
      width: calc(100% - 2px);
    }
  }

  #luckysheet {
    margin: 0px;
    padding: 0px;
    position: absolute;
    width: 100%;
    left: 0px;
    top: 30px;
    bottom: 0px;
  }
}
</style>

